package cn.com.edaily.auth.realm;

import cn.com.edaily.auth.service.AuthService;
import cn.com.edaily.cmp.User;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class AuthorizeRealm extends AuthorizingRealm {

	@Autowired
	private AuthService authService;

	/**
	 * 认证
	 *
	 * @param token
	 * @return
	 * @throws AuthenticationException
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
		//校验密码正确性(查找用户md5hash比较密码)
		List<User> users = authService.findUsersByUsername(usernamePasswordToken.getUsername());
		if (CollectionUtils.isEmpty(users)) {
			throw new UnknownAccountException("用户不存在");
		}
		User user = users.get(0);
		String databasePassword = new Md5Hash(usernamePasswordToken.getPassword(), user.getSalt()).toString();
		if (user.getPassword().equals(databasePassword)) {
			return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), getName());
		}
		throw new AuthenticationException("用户名或密码错误");
	}

	/**
	 * 授权
	 * @param principals
	 * @return
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		return null;
	}
}
